<template>
    <div class="sales-management-container">
      <van-pull-refresh v-model="refreshing" @refresh="onRefresh">

      <van-tabs v-model="activeTab" swipeable>
        <!-- 销售订单标签页 -->
        <van-tab title="销售订单">
          <div class="action-bar">
            <van-button type="primary" @click="showSalesOrderForm(null)">
              新增订单
            </van-button>
            <van-search
              v-model="salesOrderSearch"
              placeholder="搜索客户名称"
              @search="onSearchSalesOrder"
            />
          </div>
          
          <van-list
            v-model:loading="salesOrderLoading"
            :finished="salesOrderFinished"
            finished-text="没有更多了"
            @load="onLoadSalesOrder"
          >
            <van-swipe-cell v-for="order in salesOrderList" :key="order.salesOrderId">
              <van-card
                :title="order.name"
                :desc="`订单日期: ${formatDate(order.orderDate)}`"
              >
                <template #tags>
                  <van-tag plain type="primary" style="margin-right: 5px;">
                    {{ formatStatus(order.status) }}
                  </van-tag>
                  <van-tag plain type="danger">
                    ¥{{ order.totalAmount }}
                  </van-tag>
                </template>
                <template #footer>
                  <van-button size="mini" @click="showSalesOrderForm(order)">
                    编辑
                  </van-button>
                 
                </template>
              </van-card>
              
            </van-swipe-cell>
          </van-list>
        </van-tab>
  
        <!-- 客户管理标签页 -->
        <van-tab title="客户管理">
          <div class="action-bar">
            <van-button type="primary" @click="showCustomerForm(null)">
              新增客户
            </van-button>
            <van-search
              v-model="customerSearch"
              placeholder="搜索客户名称"
              @search="onSearchCustomer"
            />
          </div>
          
          <van-list
            v-model:loading="customerLoading"
            :finished="customerFinished"
            finished-text="没有更多了"
            @load="onLoadCustomer"
          >
            <van-swipe-cell v-for="customer in customerList" :key="customer.customerId">
              <van-card
                :title="customer.name"
                :desc="`联系人: ${customer.contactPerson}`"
              >
                <template #tags>
                  <van-tag plain type="primary" style="margin-right: 5px;">
                    {{ customer.contactPhone }}
                  </van-tag>
                  <van-tag plain type="success">
                    {{ customer.contactEmail }}
                  </van-tag>
                </template>
                <template #footer>
                  <van-button size="mini" @click="showCustomerForm(customer)">
                    编辑
                  </van-button>
                  
                </template>
              </van-card>
            </van-swipe-cell>
          </van-list>
        </van-tab>
      </van-tabs>
    </van-pull-refresh>



      <!-- 销售订单表单对话框 -->
      <van-dialog
        v-model:show="showSalesOrderDialog"
        :title="currentSalesOrder ? '编辑订单' : '新增订单'"
        show-cancel-button
        @confirm="submitSalesOrderForm"
      >
        <van-form ref="salesOrderFormRef">
          <van-cell-group inset>
            <van-field
              v-model="salesOrderForm.name"
              label="客户名称"
              placeholder="请输入客户名称"
              :rules="[{ required: true, message: '请填写客户名称' }]"
            />
            <van-field
              v-model="salesOrderForm.orderDate"
              label="订单日期"
              placeholder="请选择订单日期"
              readonly
              @click="showSalesOrderDatePicker = true"
              :rules="[{ required: true, message: '请选择订单日期' }]"
            />
            <van-field
              v-model="salesOrderForm.status"
              label="订单状态"
              placeholder="请选择订单状态"
              readonly
              @click="showSalesOrderStatusPicker = true"
              :rules="[{ required: true, message: '请选择订单状态' }]"
            />
            <van-field
              v-model="salesOrderForm.totalAmount"
              label="订单金额"
              placeholder="请输入订单金额"
              type="number"
              :rules="[{ required: true, message: '请填写订单金额' }]"
            />
          </van-cell-group>
        </van-form>
      </van-dialog>
  
      <!-- 客户表单对话框 -->
      <van-dialog
        v-model:show="showCustomerDialog"
        :title="currentCustomer ? '编辑客户' : '新增客户'"
        show-cancel-button
        @confirm="submitCustomerForm"
      >
        <van-form ref="customerFormRef">
          <van-cell-group inset>
            <van-field
              v-model="customerForm.name"
              label="客户名称"
              placeholder="请输入客户名称"
              :rules="[{ required: true, message: '请填写客户名称' }]"
            />
            <van-field
              v-model="customerForm.contactPerson"
              label="联系人"
              placeholder="请输入联系人"
            />
            <van-field
              v-model="customerForm.contactEmail"
              label="联系邮箱"
              placeholder="请输入联系邮箱"
              :rules="[{ type: 'email', message: '请输入正确的邮箱格式' }]"
            />
            <van-field
              v-model="customerForm.contactPhone"
              label="联系电话"
              placeholder="请输入联系电话"
            />
            <van-field
              v-model="customerForm.address"
              label="客户地址"
              placeholder="请输入客户地址"
              type="textarea"
              rows="2"
              autosize
            />
          </van-cell-group>
        </van-form>
      </van-dialog>
  
      <!-- 日期选择器 -->
      <van-popup v-model:show="showSalesOrderDatePicker" position="bottom">
        <van-date-picker
          v-model="salesOrderDate"
          @confirm="onConfirmSalesOrderDate"
          @cancel="showSalesOrderDatePicker = false"
        />
      </van-popup>
  
      <!-- 状态选择器 -->
      <van-popup v-model:show="showSalesOrderStatusPicker" position="bottom">
        <van-picker
          :columns="statusOptions"
          @confirm="onConfirmSalesOrderStatus"
          @cancel="showSalesOrderStatusPicker = false"
        />
      </van-popup>
    </div>
  </template>
  
  <script setup>
  const refreshing = ref(false);

  import { ref, reactive, onMounted } from 'vue'
  import { Dialog, Toast } from 'vant'
  import { formatDate } from '@/utils/dateUtil'
  import { 
  getSalesOrderList, 
  createSalesOrder, 
  updateSalesOrder, 
  deleteSalesOrder,
  getCustomerList,
  createCustomer,
  updateCustomer,
  deleteCustomer
} from '@/api/sales'
  // 销售订单相关状态
  const activeTab = ref(0)
  const salesOrderList = ref([])
  const salesOrderLoading = ref(false)
  const salesOrderFinished = ref(false)
  const salesOrderSearch = ref('')
  const currentSalesOrder = ref(null)
  const showSalesOrderDialog = ref(false)
  const salesOrderFormRef = ref(null)
  const showSalesOrderDatePicker = ref(false)
  const showSalesOrderStatusPicker = ref(false)
  const salesOrderDate = ref([])
  
  // 客户相关状态
  const customerList = ref([])
  const customerLoading = ref(false)
  const customerFinished = ref(false)
  const customerSearch = ref('')
  const currentCustomer = ref(null)
  const showCustomerDialog = ref(false)
  const customerFormRef = ref(null)
  
  // 表单数据
  const salesOrderForm = reactive({
    salesOrderId: null,
    name: '',
    orderDate: '',
    status: 'pending',
    totalAmount: 0
  })
  
  const customerForm = reactive({
    customerId: null,
    name: '',
    contactPerson: '',
    contactEmail: '',
    contactPhone: '',
    address: ''
  })
  
  // 状态选项
  const statusOptions = [
    { text: '待处理', value: 'pending' },
    { text: '已发货', value: 'shipped' },
    { text: '已完成', value: 'completed' }
  ]
  
  // 加载销售订单数据
  const onLoadSalesOrder = async () => {
  try {
    // 如果是下拉刷新，重置列表
    if (refreshing.value) {
      salesOrderList.value = [];
      refreshing.value = false;
    }
    
    salesOrderLoading.value = true;
    const res = await getSalesOrderList({ 
      search: salesOrderSearch.value,
      page: Math.ceil(salesOrderList.value.length / 10) + 1,
      pageSize: 10
    });
    
    if (res.data?.list?.length > 0) {
      salesOrderList.value = [...salesOrderList.value, ...res.data.list];
    } else {
      salesOrderFinished.value = true;
    }
  } catch (error) {
    Toast.fail('加载订单列表失败');
  } finally {
    salesOrderLoading.value = false;
  }
};
  
const onRefresh = () => {
  // 重置所有状态
  salesOrderFinished.value = false;
  salesOrderLoading.value = true;
  
  // 根据当前标签页决定刷新哪个列表
  if (activeTab.value === 0) {
    salesOrderList.value = [];
    onLoadSalesOrder();
  } else {
    customerList.value = [];
    onLoadCustomer();
  }
};
const onLoadCustomer = async () => {
  try {
    if (refreshing.value) {
      customerList.value = [];
      refreshing.value = false;
    }
    
    customerLoading.value = true;
    const res = await getCustomerList({ 
      search: customerSearch.value,
      page: Math.ceil(customerList.value.length / 10) + 1,
      pageSize: 10
    });
    
    if (res.data?.list?.length > 0) {
      customerList.value = [...customerList.value, ...res.data.list];
    } else {
      customerFinished.value = true;
    }
  } catch (error) {
    Toast.fail('加载客户列表失败');
  } finally {
    customerLoading.value = false;
  }
};
  // 搜索销售订单
  const onSearchSalesOrder = () => {
    salesOrderList.value = []
    salesOrderFinished.value = false
    salesOrderLoading.value = true
    onLoadSalesOrder()
  }
  
  // 搜索客户
  const onSearchCustomer = () => {
    customerList.value = []
    customerFinished.value = false
    customerLoading.value = true
    onLoadCustomer()
  }
  
  // 显示销售订单表单
  const showSalesOrderForm = (order) => {
    if (order) {
      currentSalesOrder.value = order
      Object.assign(salesOrderForm, order)
    } else {
      currentSalesOrder.value = null
      resetSalesOrderForm()
    }
    showSalesOrderDialog.value = true
  }
  
  // 显示客户表单
  const showCustomerForm = (customer) => {
    if (customer) {
      currentCustomer.value = customer
      Object.assign(customerForm, customer)
    } else {
      currentCustomer.value = null
      resetCustomerForm()
    }
    showCustomerDialog.value = true
  }
  
  // 重置销售订单表单
  const resetSalesOrderForm = () => {
    salesOrderForm.salesOrderId = null
    salesOrderForm.name = ''
    salesOrderForm.orderDate = ''
    salesOrderForm.status = 'pending'
    salesOrderForm.totalAmount = 0
  }
  
  // 重置客户表单
  const resetCustomerForm = () => {
    customerForm.customerId = null
    customerForm.name = ''
    customerForm.contactPerson = ''
    customerForm.contactEmail = ''
    customerForm.contactPhone = ''
    customerForm.address = ''
  }
  
  // 提交销售订单表单
  const submitSalesOrderForm = async () => {
  try {
    await salesOrderFormRef.value.validate()
    
    if (currentSalesOrder.value) {
      await updateSalesOrder(currentSalesOrder.value.salesOrderId, salesOrderForm)
      Toast.success('订单更新成功')
    } else {
      await createSalesOrder(salesOrderForm)
      Toast.success('订单创建成功')
    }
    
    showSalesOrderDialog.value = false
    salesOrderList.value = [] // 清空列表
    salesOrderFinished.value = false
    onLoadSalesOrder() // 重新加载
  } catch (error) {
    console.error('操作失败:', error)
  }
}
  
  // 提交客户表单
  const submitCustomerForm = async () => {
  try {
    await customerFormRef.value.validate()
    
    if (currentCustomer.value) {
      await updateCustomer(currentCustomer.value.customerId, customerForm)
      Toast.success('客户更新成功')
    } else {
      await createCustomer(customerForm)
      Toast.success('客户创建成功')
    }
    
    showCustomerDialog.value = false
    customerList.value = [] // 清空列表
    customerFinished.value = false
    onLoadCustomer() // 重新加载
  } catch (error) {
    console.error('操作失败:', error)
  }
}
  

  

  
  // 确认订单日期选择
  const onConfirmSalesOrderDate = (value) => {
    salesOrderForm.orderDate = `${value.getFullYear()}-${String(value.getMonth() + 1).padStart(2, '0')}-${String(value.getDate()).padStart(2, '0')}`
    showSalesOrderDatePicker.value = false
  }
  
  // 确认订单状态选择
  const onConfirmSalesOrderStatus = (value) => {
    salesOrderForm.status = value.selectedValues[0]
    showSalesOrderStatusPicker.value = false
  }
  
  // 格式化状态显示
  const formatStatus = (status) => {
    const option = statusOptions.find(opt => opt.value === status)
    return option ? option.text : status
  }
  
  // 初始化加载数据
  onMounted(() => {
    onLoadSalesOrder()
    onLoadCustomer()
  })
  </script>
  
  <style scoped>
  .sales-management-container {
    padding: 10px;
  }
  
  .action-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 10px;
  }
  
  .van-card {
    margin-bottom: 10px;
  }
  
  .van-tag {
    margin-top: 5px;
  }
  </style>